package com.ws.strategy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.ResultUtils;
import com.domain.dto.UserShowInfo;
import com.domain.entity.ChatMessage;
import com.domain.entity.User;
import com.ws.schedule.MessageSync;
import com.ws.message.ChatMessageDto;
import com.ws.message.ChatMessageVo;
import com.exception.BusinessException;
import com.service.UsersService;
import com.ws.MessageManager;
import com.ws.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.common.ErrorCode.FORBIDDEN;
import static com.ws.message.MessageType.PRIVATE_CHAT;

@Component
public class PrivateMessageHandler implements MessageHandler {
    private SessionManager sessionManager;
    private MessageManager messageManager;
    private UsersService userService;
    private MessageSync messageSync;

    @Override
    public Integer getMesType() {
        return PRIVATE_CHAT;
    }

    @Autowired
    public PrivateMessageHandler(SessionManager sessionManager, MessageManager messageManager, UsersService userService, MessageSync messageSync) {
        this.sessionManager = sessionManager;
        this.messageManager = messageManager;
        this.userService = userService;
        this.messageSync = messageSync;
    }

    @Override
    public void handleMessage(String messageJson) {
        ChatMessageVo chatMessageVo = JSONUtil.toBean(messageJson, ChatMessageVo.class);
        //解析消息
        ChatMessageDto chatMessageDto = messageManager.getChatMessageDto(chatMessageVo);
        //校验参数
        checkParam(chatMessageDto);
        //发送消息
        sessionManager.privateChat(JSONUtil.toJsonStr(ResultUtils.success(chatMessageDto)),
                chatMessageVo.getSenderId(),
                chatMessageVo.getReceiverId());
        ChatMessage chatMessage = BeanUtil.copyProperties(chatMessageDto, ChatMessage.class);
        //消息持久化，放入redis中，使用zset存储，value为mes,score为sendtime,privatekey是 private:uuid  groupkey是 group:teamId
        messageManager.addMessageRedisCache(chatMessage);
    }

    private void checkParam(ChatMessageDto chatMessageDto) {
        Long receiverId = chatMessageDto.getReceiverId();
        Long senderId = chatMessageDto.getSenderId();
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("id", receiverId);
        User receicer = userService.getOne(wrapper1);
        if (receicer == null) {
            sessionManager.sendMessage(JSONUtil.toJsonStr(ResultUtils.error(FORBIDDEN, "接收用户不存在!")), senderId);
        }
        //是否有这个用户，可以用布隆过滤器来优化性能，不必要去查数据库
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", senderId);
        User sender = userService.getOne(wrapper);
        if (sender == null) {
            throw new BusinessException(FORBIDDEN, "发送用户不存在");
        }
        if (!sender.getFriendList().contains(receiverId.toString())) {
            sessionManager.sendMessage(JSONUtil.toJsonStr(ResultUtils.error(FORBIDDEN, "不是好友!")), senderId);
        }
        UserShowInfo senderInfo = BeanUtil.copyProperties(sender, UserShowInfo.class);
        UserShowInfo receiverInfo = BeanUtil.copyProperties(receicer, UserShowInfo.class);
        chatMessageDto.setSender(senderInfo);
        chatMessageDto.setReceiver(receiverInfo);
    }


}
